package com.ocom.netty.mj.service.impl;

import cn.hutool.core.util.HexUtil;
import com.alibaba.fastjson.JSON;
import com.ocom.common.resp.RespMachMessage;
import com.ocom.common.utils.DateUtil;
import com.ocom.common.utils.IPUtils;
import com.ocom.common.vo.VerifyAccessVo;
import com.ocom.netty.mj.client.AiotClient;
import com.ocom.netty.mj.client.SrvpAccessDeviceClient;
import com.ocom.netty.mj.resp.*;
import com.ocom.netty.mj.ropo.TcpServiceRopo;
import com.ocom.netty.mj.service.CompanyService;
import com.ocom.netty.mj.service.MachTcpService;
import com.ocom.netty.mj.util.NumConvertUtil;
import com.ocom.redis.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Slf4j
@Service
@Resource
public class MachTcpServiceImpl implements MachTcpService {

    Logger logger= LoggerFactory.getLogger(MachTcpServiceImpl.class);

    @Autowired
    private AiotClient aiotClientService;

    @Autowired
    private SrvpAccessDeviceClient accessDeviceClient;

    @Autowired
    private CompanyService companyService;

    @Resource
    RedisUtil redisUtil;

    //签到 (0x0001)
    @Override
    public byte[] sign(TcpServiceRopo tcpServiceRopo) throws Exception {
        //Tcp参数
        //单位编号
//        String companyId=tcpServiceRopo.getCommandParam().substring(0,12);
//        //固件升级组号
//        String ues1=tcpServiceRopo.getCommandParam().substring(12,16);
//        //固件版本长度
//        String ues2=tcpServiceRopo.getCommandParam().substring(16,18);
        //固件版本
        String ues3=tcpServiceRopo.getCommandParam().substring(18,tcpServiceRopo.getCommandParam().length()-60);

        ues3=NumConvertUtil.hexStringToString(ues3);

        //要返回的对象
        TcpServiceRopo resp=new TcpServiceRopo();

        //赋返回值  全是16进制字符串
        resp.setMachId(tcpServiceRopo.getMachId());
        resp.setEdition(tcpServiceRopo.getEdition());
        resp.setType(tcpServiceRopo.getType());
        resp.setPackageNum(tcpServiceRopo.getPackageNum());
        resp.setCommandType(tcpServiceRopo.getCommandType());

        //响应写死
        resp.setRespTip("02");
        //随机 sessionid
        Random rand = new Random();
        StringBuilder session = new StringBuilder();
        for (int i=0;i<4;i++){
            Integer j= rand.nextInt(254);
            session.append(NumConvertUtil.IntToHexStringNum(j++,2));
        }
        resp.setSessionId(session.toString());

        redisUtil.hmSet("tcpMach:"+tcpServiceRopo.getMachId(),"session",session.toString());
        redisUtil.hmSet("tcpMach:"+tcpServiceRopo.getMachId(),"companyId",0);
        redisUtil.hmSet("tcpMach:"+tcpServiceRopo.getMachId(),"host", IPUtils.getHostIp());


        //获取企业Id
        Map<String,Object> map=companyService.getCompanyId(tcpServiceRopo.getMachId());
        if(!(boolean)map.get("result")){
            resp.setCommandParam((String)map.get("code"));
            String rc=resp.getHexStr();
            return  HexUtil.decodeHex(rc);
        }
        Integer companyIdres = (Integer) map.get("companyId");


        RespMachMessage respMachMessage1 = accessDeviceClient.getDeviceFlag(companyIdres.longValue(), tcpServiceRopo.getMachId(), ues3, 2);//
        logger.info("心跳#分库请求:请求参数:【{}】,返回参数:【{}】",tcpServiceRopo.getMachId(),respMachMessage1);
        logger.info("respMachMessage="+respMachMessage1);
        if (!respMachMessage1.getCode().equals("0000")) {
            resp.setCommandParam("0003");
            String rc = resp.getHexStr();
           return  HexUtil.decodeHex(rc);
        }

        //固件  Aiot调用
        RespMachMessage respMachMessageAiot=aiotClientService.GetMjDeviceVersion(tcpServiceRopo.getMachId(),ues3,2);
        logger.info("心跳#Aiot请求:请求参数:【{}】,返回参数:【{}】",tcpServiceRopo.getMachId(),respMachMessageAiot);
        if(!respMachMessageAiot.getCode().equals("0000") && !respMachMessageAiot.getCode().equals("0014")){
            resp.setCommandParam("3004");
            String rc = resp.getHexStr();
            return  HexUtil.decodeHex(rc);
        }
        Map<String,Object> objectMap2=(Map<String, Object>) JSON.parse(JSON.toJSONString(respMachMessageAiot.getData()));


        //黑名单/智慧校园白名单
        String updateWhite="1";
        //固定是否更新
        String updateMach="1";
        //门禁时区是否更新
        String updateDoorZoon="1";
        //门禁权限组是否更新
        String updateDoorWhite="1";

        Map<String,Object> map1= JSON.parseObject(JSON.toJSONString(respMachMessage1.getData()), Map.class);
        System.out.println(respMachMessage1);
        updateWhite=String.valueOf((Integer) map1.get("listUpdate")) ;
//        updateMach=String.valueOf((Integer) map1.get("firmwareUpdate")) ;
        if(respMachMessageAiot.getCode().equals("0000")){
            updateWhite =String .valueOf((Integer) objectMap2.get("firmwareUpdate"));
        }else{
            updateWhite ="0" ;
        }
        updateDoorZoon=String.valueOf((Integer) map1.get("accontimeUpdate")) ;
        updateDoorWhite=String.valueOf((Integer) map1.get("acconpermissionUpdate")) ;

        //响应结果  67个字节
        String param= "00000a02e69801000022021811223200000000000100000000000000000000000000000000000000000000000000000000000000000000000101000000000000000000";

        //系统时间
        Date now = new Date();
        String sysDate=DateFormatUtils.format(now, "YMMddHHmmss").substring(2);
        StringBuilder stringBuilder=new StringBuilder(param);
        stringBuilder.replace(18,30,sysDate);

        stringBuilder.replace(13,14,updateWhite);
        stringBuilder.replace(41,42,updateMach);
        stringBuilder.replace(113,114,updateDoorZoon);
        stringBuilder.replace(115,116,updateDoorWhite);

        resp.setCommandParam(stringBuilder.toString());

        String rc=resp.getHexStr();
        System.out.println(rc);
        return  HexUtil.decodeHex(rc);
    }

    //心跳 (0x0003)
    @Override
    public byte[] heartbeat(TcpServiceRopo tcpServiceRopo) throws Exception {

        //要返回的对象
        TcpServiceRopo resp=new TcpServiceRopo();

        //赋返回值  全是16进制字符串
        resp.setMachId(tcpServiceRopo.getMachId());
        resp.setEdition(tcpServiceRopo.getEdition());
        resp.setType(tcpServiceRopo.getType());
        resp.setPackageNum(tcpServiceRopo.getPackageNum());
        resp.setCommandType(tcpServiceRopo.getCommandType());

        //响应写死
        resp.setRespTip("02");
        //随机
        resp.setSessionId(tcpServiceRopo.getSessionId());

        //判断sessionId
        if(!checkSessionId(tcpServiceRopo)){
            resp.setCommandParam("0001");
            String rc=resp.getHexStr();
            return  HexUtil.decodeHex(rc);
        }


        //tcp参数
        //离线记录次数
        String leaveTimes=tcpServiceRopo.getCommandParam().substring(0,8);
        //离线标识
        String leaveTip=tcpServiceRopo.getCommandParam().substring(8,16);

//        System.out.println(leaveTimes);
//        System.out.println(leaveTip);

        //响应结果  56个字节
        String param= "0000010000220221093044000000000007000000000000000008090000000000000000000000000000000000000000000000000000000000";

        //获取企业Id
        Map<String,Object> map=companyService.getCompanyId(tcpServiceRopo.getMachId());
        if(!(boolean)map.get("result")){
            resp.setCommandParam((String)map.get("code"));
            String rc=resp.getHexStr();
            return  HexUtil.decodeHex(rc);
        }
        Integer companyIdres=(Integer)map.get("companyId");

        RespMachMessage respMachMessage1=accessDeviceClient.getDeviceFlag(companyIdres.longValue(),tcpServiceRopo.getMachId(),"",1);//
        if(!respMachMessage1.getCode().equals("0000")){
            resp.setCommandParam("0003");
            String rc=resp.getHexStr();
            return  HexUtil.decodeHex(rc);
        }
//        System.out.println(respMachMessage1);

        //固件  Aiot调用
        RespMachMessage respMachMessageAiot=aiotClientService.GetMjDeviceVersion(tcpServiceRopo.getMachId(),"",2);
        logger.info("心跳#Aiot请求:请求参数:【{}】,返回参数:【{}】",tcpServiceRopo.getMachId(),respMachMessageAiot);
        if(!respMachMessageAiot.getCode().equals("0000") && !respMachMessageAiot.getCode().equals("0014")){
            resp.setCommandParam("3004");
            String rc = resp.getHexStr();
            return  HexUtil.decodeHex(rc);
        }
        Map<String,Object> objectMap2=(Map<String, Object>) JSON.parse(JSON.toJSONString(respMachMessageAiot.getData()));

        //系统时间
        Date now = new Date();
        String sysDate=DateFormatUtils.format(now, "YMMddHHmmss").substring(2);
        StringBuilder stringBuilder=new StringBuilder(param);
        stringBuilder.replace(10,22,sysDate);

        Map<String,Object> map1= JSON.parseObject(JSON.toJSONString(respMachMessage1.getData()), Map.class);

        //黑名单/智慧校园白名单
        String updateList=String.valueOf((Integer) map1.get("listUpdate")) ;

        //心跳固件更新标识
//        String updateHeartbeat=String.valueOf((Integer) map1.get("firmwareUpdate")) ;
        String updateHeartbeat= "";
        if(!respMachMessageAiot.getCode().equals("0014")){
            updateHeartbeat =String.valueOf((Integer) objectMap2.get("firmwareUpdate")) ;
        }else{
            updateHeartbeat ="0" ;
        }


        //门禁时区更新标识
        String updateDoorTime=String.valueOf((Integer) map1.get("accontimeUpdate")) ;

        //门禁权限组更新标识
        String updateDoorAuth=String.valueOf((Integer) map1.get("acconpermissionUpdate")) ;

        //密钥更新标识
        String keyUpdate=String.valueOf((Integer) map1.get("keyUpdate")) ;

        stringBuilder.replace(9,10,updateList);
        stringBuilder.replace(33,34,updateHeartbeat);
        stringBuilder.replace(51,52,updateDoorTime);
        stringBuilder.replace(53,54,updateDoorAuth);
        stringBuilder.replace(55,56,keyUpdate);

//        stringBuilder.replace(9,10,"1");
//        stringBuilder.replace(33,34,"1");
//        stringBuilder.replace(51,52,"1");
//        stringBuilder.replace(53,54,"1");
//        stringBuilder.replace(55,56,"1");

        resp.setCommandParam(stringBuilder.toString());
//        System.out.println(resp);
        String rc=resp.getHexStr();
//        System.out.println(rc);
        return  HexUtil.decodeHex(rc);
    }

    //门禁离线开门数据上传（0x8001）
    @Override
    public byte[] uploadData(TcpServiceRopo tcpServiceRopo) throws Exception {
        //TODO 直接写死的参数
//        tcpServiceRopo.setCommandParam("000000010000000100000001220223090909");
        //tcp参数
        //记录流水号
        String recodeNo=tcpServiceRopo.getCommandParam().substring(0,8);
        //物理卡号
        String cardNo=tcpServiceRopo.getCommandParam().substring(8,16);
        //学号
        String studentNo=tcpServiceRopo.getCommandParam().substring(16,24);
        //时间 Yymmddhhmmss
        String time=tcpServiceRopo.getCommandParam().substring(24,36);
        StringBuilder stringBuilder2=new StringBuilder(time);
        stringBuilder2.insert(10,":");
        stringBuilder2.insert(8,":");
        stringBuilder2.insert(6," ");
        stringBuilder2.insert(4,"-");
        stringBuilder2.insert(2,"-");
        stringBuilder2.insert(0,"20");

        time=stringBuilder2.toString();
        //"2021-02-23 10:12:09"

        //要返回的对象
        TcpServiceRopo resp=new TcpServiceRopo();

        //赋返回值  全是16进制字符串
        resp.setMachId(tcpServiceRopo.getMachId());
        resp.setEdition(tcpServiceRopo.getEdition());
        resp.setType(tcpServiceRopo.getType());
        resp.setPackageNum(tcpServiceRopo.getPackageNum());
        resp.setCommandType(tcpServiceRopo.getCommandType());
//        resp.setCommandType("8003");

        //响应写死
        resp.setRespTip("02");
        //随机
        resp.setSessionId(tcpServiceRopo.getSessionId());

        //判断sessionId
        if(!checkSessionId(tcpServiceRopo)){
            resp.setCommandParam("0001");
            String rc=resp.getHexStr();
            return  HexUtil.decodeHex(rc);
        }

        //获取企业Id
        Map<String,Object> map=companyService.getCompanyId(tcpServiceRopo.getMachId());
        if(!(boolean)map.get("result")){
            resp.setCommandParam((String)map.get("code"));
            String rc=resp.getHexStr();
            return  HexUtil.decodeHex(rc);
        }
        Integer companyIdres=(Integer)map.get("companyId");

        RespMachMessage respMachMessage1=accessDeviceClient.saveAccessRecord(companyIdres.longValue(),tcpServiceRopo.getMachId(),NumConvertUtil.HexStringToInt(studentNo).longValue(),time,1L);//
        logger.info("companyIdres:"+companyIdres);
        logger.info("tcpServiceRopo:"+tcpServiceRopo.toString());
        logger.info("studentNo:"+studentNo);
        logger.info("time:"+time);
        logger.info("上传结果respMachMessage1:"+respMachMessage1.toString());
        if(!respMachMessage1.getCode().equals("0000")){
//            resp.setCommandParam("0003");
//            String rc=resp.getHexStr();
//            return  HexUtil.decodeHex(rc);
            logger.info("记录异常日志上传");
        }
//        System.out.println(respMachMessage1);

        //响应结果  6个字节
        String param= "000000000000";

        StringBuilder stringBuilder=new StringBuilder(param);

        //返回请求的记录号
        stringBuilder.replace(4,12,recodeNo);

        resp.setCommandParam(stringBuilder.toString());
        String rc=resp.getHexStr();
        return  HexUtil.decodeHex(rc);
    }

    //卡认证开门命令（0x8003）
    @Override
    public byte[] openDoorCommand(TcpServiceRopo tcpServiceRopo) throws Exception {
        //tcp参数
//        tcpServiceRopo.setCommandParam("02000000000000000000000000000000000000");
        //类型
        String type=tcpServiceRopo.getCommandParam().substring(0,2);

        String cardNo="";
        String handleType="";
        String openNo="";
        if(type.equals("03")){
            //4字节IC卡物理卡号或逻辑卡号
            cardNo=tcpServiceRopo.getCommandParam().substring(2,18);
            //操作类型
            handleType=tcpServiceRopo.getCommandParam().substring(18,20);
            //开门序列号
            openNo=tcpServiceRopo.getCommandParam().substring(20,46);
        }else{
            //4字节IC卡物理卡号或逻辑卡号
            cardNo=tcpServiceRopo.getCommandParam().substring(2,10);
            //操作类型
            handleType=tcpServiceRopo.getCommandParam().substring(10,12);
            //开门序列号
            openNo=tcpServiceRopo.getCommandParam().substring(12,38);
        }


        //要返回的对象
        TcpServiceRopo resp=new TcpServiceRopo();

        //赋返回值  全是16进制字符串
        resp.setMachId(tcpServiceRopo.getMachId());
        resp.setEdition(tcpServiceRopo.getEdition());
        resp.setType(tcpServiceRopo.getType());
        resp.setPackageNum(tcpServiceRopo.getPackageNum());
        resp.setCommandType(tcpServiceRopo.getCommandType());

        //响应写死
        resp.setRespTip("02");
        //随机
        resp.setSessionId(tcpServiceRopo.getSessionId());

        //判断sessionId
        if(!checkSessionId(tcpServiceRopo)){
            resp.setCommandParam("0001");
            String rc=resp.getHexStr();
            return  HexUtil.decodeHex(rc);
        }

        //获取企业Id
        Map<String,Object> map=companyService.getCompanyId(tcpServiceRopo.getMachId());
        if(!(boolean)map.get("result")){
            resp.setCommandParam((String)map.get("code"));
            String rc=resp.getHexStr();
            return  HexUtil.decodeHex(rc);
        }
        Integer companyIdres=(Integer)map.get("companyId");

        VerifyAccessVo verifyAccessVo=new VerifyAccessVo();
        verifyAccessVo.setCompanyId(companyIdres.longValue());
        verifyAccessVo.setMachNo(tcpServiceRopo.getMachId());
        verifyAccessVo.setType(Integer.valueOf(type));
        verifyAccessVo.setIdnum(cardNo);
//        verifyAccessVo.setIdnum("1");
        verifyAccessVo.setOperatetype(1);
        verifyAccessVo.setSerialnumber(openNo);
        verifyAccessVo.setTime(DateUtil.getDateTime());
        System.out.println(verifyAccessVo);

        RespMachMessage respMachMessage1=accessDeviceClient.verifyAccess(verifyAccessVo);//
        System.out.println(respMachMessage1);
        if(!respMachMessage1.getCode().equals("0000")){
            resp.setCommandParam(respMachMessage1.getCode());
            String rc=resp.getHexStr();
            return  HexUtil.decodeHex(rc);
        }

        //{code='0000', msg='成功', data={result=1, msg=无开门权限, overopentimes=0, balckFlag=0, overdueFlag=0, type=0, idnum=1, permissionsFlag=1}}

        Map<String,Object> map2= JSON.parseObject(JSON.toJSONString(respMachMessage1.getData()), Map.class);
        //响应结果
        String param= "000000000000000000000000000000";

        StringBuilder stringBuilder=new StringBuilder(param);

        if((Integer)map2.get("result")!=0){
            stringBuilder.replace(0,4,"0003");
        }else{
            //TODO 存开门记录
            accessDeviceClient.saveAccessRecord(companyIdres.longValue(),tcpServiceRopo.getMachId(),NumConvertUtil.HexStringToInt(cardNo).longValue(), DateUtil.getDateTime(),1L);//
        }

        //请求类型 1
        stringBuilder.replace(4,6,type);
        //卡号/人员编号 4
        stringBuilder.replace(6,14,NumConvertUtil.IntToHexStringNum((Integer) map2.get("idnum"),8));
        //黑名单标志  1
        stringBuilder.replace(23,24,map2.get("balckFlag").toString());
        //是否有开门权限标志  1
        stringBuilder.replace(25,26,map2.get("permissionsFlag").toString());
        //开门次数超限标志  1
        stringBuilder.replace(27,28,map2.get("overopentimes").toString());
        //卡已过期标志  1
//        stringBuilder.replace(29,30,map2.get("overdueFlag").toString());



        resp.setCommandParam(stringBuilder.toString());
        String rc=resp.getHexStr();
        System.out.println(rc);
        return  HexUtil.decodeHex(rc);
    }

    //门禁码在线/离线消费（0x8004）
    @Override
    public byte[] doorPay(TcpServiceRopo tcpServiceRopo) throws Exception {
        //tcp参数
        //记录号 4
        String recode=tcpServiceRopo.getCommandParam().substring(0,8);
        //开门序列号 13
        String openNo=tcpServiceRopo.getCommandParam().substring(8,34);
        //解码时间 6
        String codeTime=tcpServiceRopo.getCommandParam().substring(34,46);
        //二维码长度 1
        String length=tcpServiceRopo.getCommandParam().substring(46,48);
        //二维码内容
        String qrCode=tcpServiceRopo.getCommandParam().substring(46);

        //拆分二维码内容
        //人员Id
        String pidHex=tcpServiceRopo.getCommandParam().substring(70,78);
        Integer pId=NumConvertUtil.HexStringToInt(pidHex);

        //要返回的对象
        TcpServiceRopo resp=new TcpServiceRopo();

        //赋返回值  全是16进制字符串
        resp.setMachId(tcpServiceRopo.getMachId());
        resp.setEdition(tcpServiceRopo.getEdition());
        resp.setType(tcpServiceRopo.getType());
        resp.setPackageNum(tcpServiceRopo.getPackageNum());
        resp.setCommandType(tcpServiceRopo.getCommandType());

        //响应写死
        resp.setRespTip("02");
        //随机
        resp.setSessionId(tcpServiceRopo.getSessionId());

        //判断sessionId
        if(!checkSessionId(tcpServiceRopo)){
            resp.setCommandParam("0001");
            String rc=resp.getHexStr();
            return  HexUtil.decodeHex(rc);
        }

        //获取企业Id
        Map<String,Object> map=companyService.getCompanyId(tcpServiceRopo.getMachId());
        if(!(boolean)map.get("result")){
            resp.setCommandParam((String)map.get("code"));
            String rc=resp.getHexStr();
            return  HexUtil.decodeHex(rc);
        }
        Integer companyIdres=(Integer)map.get("companyId");

        VerifyAccessVo verifyAccessVo=new VerifyAccessVo();
        verifyAccessVo.setCompanyId(companyIdres.longValue());
        verifyAccessVo.setMachNo(tcpServiceRopo.getMachId());
        verifyAccessVo.setType(2);
        verifyAccessVo.setIdnum(pId.toString());
//        verifyAccessVo.setIdnum("1");
        verifyAccessVo.setOperatetype(1);
        verifyAccessVo.setSerialnumber(openNo);
        verifyAccessVo.setTime(DateUtil.getDateTime());
        System.out.println(verifyAccessVo);

        RespMachMessage respMachMessage1=accessDeviceClient.verifyAccess(verifyAccessVo);//
        System.out.println(respMachMessage1);
        if(!respMachMessage1.getCode().equals("0000")){
            resp.setCommandParam(respMachMessage1.getCode());
            String rc=resp.getHexStr();
            return  HexUtil.decodeHex(rc);
        }
        //{code='0000', msg='成功', data={result=1, msg=无开门权限, overopentimes=0, balckFlag=0, overdueFlag=0, type=0, idnum=1, permissionsFlag=1}}

        Map<String,Object> map2= JSON.parseObject(JSON.toJSONString(respMachMessage1.getData()), Map.class);
        //响应结果
        String param= "0000";

        StringBuilder stringBuilder=new StringBuilder(param);

        if((Integer)map2.get("result")!=0){
            stringBuilder.replace(0,4,"0003");
        }else{
            //TODO 存开门记录
            accessDeviceClient.saveAccessRecord(companyIdres.longValue(),tcpServiceRopo.getMachId(),pId.longValue(), DateUtil.getDateTime(),1L);//
        }

        resp.setCommandParam(stringBuilder.toString());
        String rc=resp.getHexStr();
        System.out.println(rc);
        return  HexUtil.decodeHex(rc);
    }
    //获取门禁权限组（0x8008）
    @Override
    public byte[] doorAuth(TcpServiceRopo tcpServiceRopo) throws Exception {
        //tcp参数
        //获取门禁权限组 1
        String recode=tcpServiceRopo.getCommandParam();

        Integer perGroupNum=NumConvertUtil.HexStringToInt(recode);

        //要返回的对象
        TcpServiceRopo resp=new TcpServiceRopo();


        //赋返回值  全是16进制字符串
        resp.setMachId(tcpServiceRopo.getMachId());
        resp.setEdition(tcpServiceRopo.getEdition());
        resp.setType(tcpServiceRopo.getType());
        resp.setPackageNum(tcpServiceRopo.getPackageNum());
        resp.setCommandType(tcpServiceRopo.getCommandType());

        //响应写死
        resp.setRespTip("02");
        //随机
        resp.setSessionId(tcpServiceRopo.getSessionId());

        //判断sessionId
        if(!checkSessionId(tcpServiceRopo)){
            resp.setCommandParam("0001");
            String rc=resp.getHexStr();
            return  HexUtil.decodeHex(rc);
        }

        //响应结果  19个字节
        String param= "000000000000000000000000000000000000000000";
        StringBuilder stringBuilder=new StringBuilder(param);

        //时区 2个字节 二进制 16个字节对应16个时区 0000000000000000
        String timeBit="0000000000000000";
        StringBuilder stringBuilder1=new StringBuilder(timeBit);

        //获取企业Id
        Map<String,Object> map=companyService.getCompanyId(tcpServiceRopo.getMachId());
        if(!(boolean)map.get("result")){
            resp.setCommandParam((String)map.get("code"));
            String rc=resp.getHexStr();
            return  HexUtil.decodeHex(rc);
        }
        Integer companyIdres=(Integer)map.get("companyId");

        RespMachMessage respMachMessage1=accessDeviceClient.getGroupPara(companyIdres.longValue(),tcpServiceRopo.getMachId(),perGroupNum.longValue());//
        if(respMachMessage1==null){
            resp.setCommandParam("0003");
            String rc=resp.getHexStr();
            return  HexUtil.decodeHex(rc);
        }
        if(!respMachMessage1.getCode().equals("0000")){
            resp.setCommandParam("0003");
            String rc=resp.getHexStr();
            return  HexUtil.decodeHex(rc);
        }
        System.out.println(respMachMessage1);

        List<DoorAuth> list= JSON.parseObject(JSON.toJSONString(respMachMessage1.getData()), List.class);
        if(list==null || list.size()==0){
            resp.setCommandParam(param);
            String rc=resp.getHexStr();
            return  HexUtil.decodeHex(rc);
        }

        for (Object ob:list){
            DoorAuth doorAuth=JSON.parseObject(JSON.toJSONString(ob), DoorAuth.class);
            //这个是权限组号
            String hexStr=NumConvertUtil.byteToHex(doorAuth.getPergroupnum());
            stringBuilder.replace(4,6,hexStr);
            if(doorAuth.getTimezone()<=16){
                //权限组是存在的 二进制改为1
                stringBuilder1.replace(doorAuth.getTimezone()-1,doorAuth.getTimezone(),"1");
                Integer timeSize=doorAuth.getStart_endtime().size();
                //时间段数量复制
                String HexInt=NumConvertUtil.IntToHexStringNum(timeSize,2);
                stringBuilder.replace(doorAuth.getTimezone()*2+8,doorAuth.getTimezone()*2+10,HexInt);
                for (String times:doorAuth.getStart_endtime()){
                    times=times.replace("-","").replace(":","");
                    String timeHex="";
                    for (int i=0;i<=3;i++){
                        timeHex+=NumConvertUtil.IntToHexStringNum(Integer.valueOf(times.substring(i*2,(i+1)*2)),2);
                    }
                    stringBuilder.append(timeHex);
                }
            }
        }

        //二进制转16进制
        String numHex=NumConvertUtil.binaryString2hexString(stringBuilder1.toString());

        System.out.println(numHex);
        stringBuilder.replace(6,10,numHex);

        resp.setCommandParam(stringBuilder.toString());
        System.out.println(resp);
        String rc=resp.getHexStr();
        System.out.println(rc);
        return  HexUtil.decodeHex(rc);
    }
    //获取门禁日期时区表（0x8009）
    @Override
    public byte[] doorTime(TcpServiceRopo tcpServiceRopo) throws Exception {
        //要返回的对象
        TcpServiceRopo resp=new TcpServiceRopo();

        //赋返回值  全是16进制字符串
        resp.setMachId(tcpServiceRopo.getMachId());
        resp.setEdition(tcpServiceRopo.getEdition());
        resp.setType(tcpServiceRopo.getType());
        resp.setPackageNum(tcpServiceRopo.getPackageNum());
        resp.setCommandType(tcpServiceRopo.getCommandType());

        //响应写死
        resp.setRespTip("02");
        //随机
        resp.setSessionId(tcpServiceRopo.getSessionId());

        //判断sessionId
        if(!checkSessionId(tcpServiceRopo)){
            resp.setCommandParam("0001");
            String rc=resp.getHexStr();
            return  HexUtil.decodeHex(rc);
        }


        //获取企业Id
        Map<String,Object> map=companyService.getCompanyId(tcpServiceRopo.getMachId());
        if(!(boolean)map.get("result")){
            resp.setCommandParam((String)map.get("code"));
            String rc=resp.getHexStr();
            return  HexUtil.decodeHex(rc);
        }
        Integer companyIdres=(Integer)map.get("companyId");

        RespMachMessage respMachMessage1=accessDeviceClient.getZoneTime(Long.valueOf(String.valueOf(companyIdres)),tcpServiceRopo.getMachId());//
        if(!respMachMessage1.getCode().equals("0000")){
            resp.setCommandParam("0003");
            String rc=resp.getHexStr();
            return  HexUtil.decodeHex(rc);
        }
        System.out.println(respMachMessage1);

        List<Object> list= JSON.parseObject(JSON.toJSONString(respMachMessage1.getData()), List.class);

        //响应结果  7天 7个字节
        String param= "000000000000000000";
        StringBuilder stringBuilder=new StringBuilder(param);

        //特殊节日和数量
        String SpecialDate="";
        Integer Sum=0;
        for (Object ob:list){
            TimeZone timeZone1=JSON.parseObject(JSON.toJSONString(ob), TimeZone.class);
            String hexStr=NumConvertUtil.byteToHex(timeZone1.getTimeZone());
            if(timeZone1.getDate().equals("0")){
                stringBuilder.replace(4,6,hexStr);
            }else if(timeZone1.getDate().equals("1")){
                stringBuilder.replace(6,8,hexStr);
            }else if(timeZone1.getDate().equals("2")){
                stringBuilder.replace(8,10,hexStr);
            }else if(timeZone1.getDate().equals("3")){
                stringBuilder.replace(10,12,hexStr);
            }else if(timeZone1.getDate().equals("4")){
                stringBuilder.replace(12,14,hexStr);
            }else if(timeZone1.getDate().equals("5")){
                stringBuilder.replace(14,16,hexStr);
            }else if(timeZone1.getDate().equals("6")){
                stringBuilder.replace(16,18,hexStr);
            }
            //特殊日期
            if(timeZone1.getDate().length()>1){
                //特殊节日和数量
                String sDate=timeZone1.getDate().replace("-","").substring(2);
                SpecialDate+=sDate;
                SpecialDate+=hexStr;
                Sum++;
            }
        }

        if(Sum>0){
            String sumHex=NumConvertUtil.byteToHex(Sum);
            stringBuilder.append(sumHex);
            stringBuilder.append(SpecialDate);
            System.out.println(sumHex);
            System.out.println(SpecialDate);
        }else{
            stringBuilder.append("00");
        }
        resp.setCommandParam(stringBuilder.toString());
        String rc=resp.getHexStr();
        System.out.println(rc);
        return  HexUtil.decodeHex(rc);
    }
    //获取门禁日期时区表结果（0x8109）
    @Override
    public byte[] doorTimeResult(TcpServiceRopo tcpServiceRopo) throws Exception {
        //tcp参数
        //获取结果 1
        String status=tcpServiceRopo.getCommandParam();

        //要返回的对象
        TcpServiceRopo resp=new TcpServiceRopo();

        //赋返回值  全是16进制字符串
        resp.setMachId(tcpServiceRopo.getMachId());
        resp.setEdition(tcpServiceRopo.getEdition());
        resp.setType(tcpServiceRopo.getType());
        resp.setPackageNum(tcpServiceRopo.getPackageNum());
        resp.setCommandType(tcpServiceRopo.getCommandType());

        //响应写死
        resp.setRespTip("02");
        //随机
        resp.setSessionId(tcpServiceRopo.getSessionId());

        //判断sessionId
        if(!checkSessionId(tcpServiceRopo)){
            resp.setCommandParam("0001");
            String rc=resp.getHexStr();
            return  HexUtil.decodeHex(rc);
        }

        if(status.equals("00")){
            //获取企业Id
            Map<String,Object> map=companyService.getCompanyId(tcpServiceRopo.getMachId());
            if(!(boolean)map.get("result")){
                resp.setCommandParam((String)map.get("code"));
                String rc=resp.getHexStr();
                return  HexUtil.decodeHex(rc);
            }
            Integer companyIdres=(Integer)map.get("companyId");

            RespMachMessage respMachMessage1=accessDeviceClient.changeZoneTimeState(Long.valueOf(String.valueOf(companyIdres)),tcpServiceRopo.getMachId());//
            System.out.println(respMachMessage1);
            if(!respMachMessage1.getCode().equals("0000")){
                resp.setCommandParam(respMachMessage1.getCode());
                String rc=resp.getHexStr();
                return  HexUtil.decodeHex(rc);
            }
            Map<String,Integer> map2= JSON.parseObject(JSON.toJSONString(respMachMessage1.getData()), Map.class);
            if (map2.get("flag")==0) {
                resp.setCommandParam("000000");
                String rc=resp.getHexStr();
                return  HexUtil.decodeHex(rc);
            }else{
                resp.setCommandParam("0000ff");
                String rc=resp.getHexStr();
                return  HexUtil.decodeHex(rc);
            }
        }else{
            //响应结果
            // 0xff：有
            //0x00：无
            String param= "000000";
            resp.setCommandParam(param);
            String rc=resp.getHexStr();
            System.out.println(rc);
            return  HexUtil.decodeHex(rc);
        }
    }

    @Override
    public byte[] distanceOpenDoor(TcpServiceRopo tcpServiceRopo) throws Exception {
        //要返回的对象
        TcpServiceRopo resp=new TcpServiceRopo();

        //赋返回值  全是16进制字符串
        resp.setMachId(tcpServiceRopo.getMachId());
        resp.setEdition(tcpServiceRopo.getEdition());
        resp.setType(tcpServiceRopo.getType());
        resp.setPackageNum(tcpServiceRopo.getPackageNum());
        resp.setCommandType(tcpServiceRopo.getCommandType());

        //响应写死
        resp.setRespTip("02");

        resp.setCommandParam("0000");
        String rc=resp.getHexStr();
        return  HexUtil.decodeHex(rc);
    }


    //固件更新续传 (0xcc00)
    @Override
    public byte[] updateMach(TcpServiceRopo tcpServiceRopo) throws Exception {
        //tcp参数
        //已保存的上一包固件包号
        String packNo=tcpServiceRopo.getCommandParam();

        //要返回的对象
        TcpServiceRopo resp=new TcpServiceRopo();

        //赋返回值  全是16进制字符串
        resp.setMachId(tcpServiceRopo.getMachId());
        resp.setEdition(tcpServiceRopo.getEdition());
        resp.setType(tcpServiceRopo.getType());
        resp.setPackageNum(tcpServiceRopo.getPackageNum());
        resp.setCommandType(tcpServiceRopo.getCommandType());

        //响应写死
        resp.setRespTip("02");
        //随机
        resp.setSessionId(tcpServiceRopo.getSessionId());

        //判断sessionId
        if(!checkSessionId(tcpServiceRopo)){
            resp.setCommandParam("0001");
            String rc=resp.getHexStr();
            return  HexUtil.decodeHex(rc);
        }

        //获取企业Id
        Map<String,Object> map=companyService.getCompanyId(tcpServiceRopo.getMachId());
        if(!(boolean)map.get("result")){
            resp.setCommandParam((String)map.get("code"));
            String rc=resp.getHexStr();
            return  HexUtil.decodeHex(rc);
        }
        Integer companyIdres=(Integer)map.get("companyId");

        RespMachMessage respMachMessage1=aiotClientService.getBinData(companyIdres.longValue(),tcpServiceRopo.getMachId(),NumConvertUtil.HexStringToInt(packNo));//
        logger.info("获取到的二进制升级数组 respMachMessage1:"+respMachMessage1);
//        System.out.println(respMachMessage1);
        if(!respMachMessage1.getCode().equals("0000")){
            resp.setCommandParam(respMachMessage1.getCode());
            String rc=resp.getHexStr();
            return  HexUtil.decodeHex(rc);
        }

        MachUpdate machUpdate=JSON.parseObject(JSON.toJSONString(respMachMessage1.getData()), MachUpdate.class);
        System.out.println("machUpdate"+machUpdate);

        String jobId=NumConvertUtil.IntLegth(machUpdate.getJobId(),12);

        String packSize=NumConvertUtil.IntToHexStringNum(512,4);

        logger.info("machUpdate:"+machUpdate);
        //固件分为多组下传，第一组为新代码存放地址（4字节）和新代码长度（4字节）；第二组开始为固件代码。
        if(packNo.equals("0000")){
            //响应结果  6个字节
            String param= "0000"+jobId+"0000"+packSize+"00000000";
            StringBuilder stringBuilder=new StringBuilder(param);
            String size3=NumConvertUtil.IntToHexStringNum(machUpdate.getBinBlockNum(),8);
            stringBuilder.append(size3);
            resp.setCommandParam(stringBuilder.toString());
            String rc=resp.getHexStr();
            return  HexUtil.decodeHex(rc);
        }
        if(machUpdate.getBlockSize()==null){
            resp.setCommandParam("0003");
            String rc=resp.getHexStr();
            return  HexUtil.decodeHex(rc);
        }

        //响应结果  6个字节
        String param= "0000"+jobId+packNo+packSize;

        System.out.println("param");
        System.out.println(param);

   //     String binBlockNum=NumConvertUtil.IntLegth(machUpdate.getBinBlockNum(),2);

        StringBuilder stringBuilder=new StringBuilder(param);


        String HexPass="38517D798DB7DD779ECEBA5D6199FD9C661044CD35842CA6E0035F0089531E95361400514E5DC797D84F9201EA135E8716D8B80EFA1272B1764FAB2120BCC094B98C9975773C57B829CB00B82F0A61C62609A61BC73A8117CFCA3C262AB2A9759EC6A42F87431975AA5391A57B25AD8582F77F1DB4EA19006497D69063AFF29AC3F948405881043C4995E440BEAADAF7516BD16389F8408C1CDC5522414C44316764572BFDC27C608CD3522FCF97C5C12595E1EDCA9D712D5101EB6556206D319218FB1903D229FECE59D11E9FB6C52798800D63EAF6A493870FBCBA191CBFF121F4B599EC3EF5A0D1890694058768F7A23BE255D46E05ACC6B14A25DC7C5D8A8C9E1F58BAD40ECDC519DDED5C9CA5D61D4087A47073343B2AC3C4408C37A278E6EEF409C63E9992B7F49FF6DBA8D64A41B6FF5A0DFE7653152C3E524E6704BBCEC431F258D883ABD4B84179ABE3785320E9EDD2D900BC2FD93551A5C09AFFE29EC6A42F87431975AA5391A57B25AD85DB7FCBC0C6D342D3FA9A61D1599D5A92A188559ACA991D13675B867E61208153603E93D3CD4DEA8F957FA35DB31BF137B76A2534A314BC1B110A3B134144294D3C32239FABF583A24874AD167D078F1A5465CFCBD3709A238FE305DF2109DE6D7185EED07A589F935B646D6DE0C4DDADB2AF39737B80D35FADAD3CE11729B7A9F5A86715C7091663C4571CBCA84979F1";
        byte[] HexPassByte=NumConvertUtil.hexStringToByte(HexPass);
        //加密 异或
        StringBuilder newStr=new StringBuilder();
        int i=0;
        if(machUpdate.getBlockSize()>0){
            for (String str:machUpdate.getBlockData()){
                newStr.append(str);
                i++;
            }
        }
        if(i<512){
            stringBuilder.replace(20,24,NumConvertUtil.IntToHexStringNum(i,4));
            for (int j=512-i;j>0;j--){
                newStr.append("00");
            }
        }

        byte[]  newStrByte=NumConvertUtil.hexStringToByte(newStr.toString());


        for (int k=0;k<512;k++){
            newStrByte[k]= (byte) (newStrByte[k] ^ HexPassByte[k]);
        }

        System.out.println(NumConvertUtil.bytesToHexString(newStrByte));

        stringBuilder.append(NumConvertUtil.bytesToHexString(newStrByte));

        resp.setCommandParam(stringBuilder.toString());
        String rc=resp.getHexStr();
        return  HexUtil.decodeHex(rc);
    }
    //固件更新结果通知续传(0xdc00)
    @Override
    public byte[] updateMachSequel(TcpServiceRopo tcpServiceRopo) throws Exception {
//        tcpServiceRopo.setCommandParam("12345678901200");
        //tcp参数
        //JobID 6
        String recode=tcpServiceRopo.getCommandParam().substring(0,12);
        //更新结果 1
        String result=tcpServiceRopo.getCommandParam().substring(12,14);

        //要返回的对象
        TcpServiceRopo resp=new TcpServiceRopo();

        //赋返回值  全是16进制字符串
        resp.setMachId(tcpServiceRopo.getMachId());
        resp.setEdition(tcpServiceRopo.getEdition());
        resp.setType(tcpServiceRopo.getType());
        resp.setPackageNum(tcpServiceRopo.getPackageNum());
        resp.setCommandType(tcpServiceRopo.getCommandType());

        //响应写死
        resp.setRespTip("02");
        //随机
        resp.setSessionId(tcpServiceRopo.getSessionId());

        //判断sessionId
        if(!checkSessionId(tcpServiceRopo)){
            resp.setCommandParam("0001");
            String rc=resp.getHexStr();
            return  HexUtil.decodeHex(rc);
        }

        //失败
        if(result.equals("01")){
            resp.setCommandParam("000300");
            String rc=resp.getHexStr();
            return  HexUtil.decodeHex(rc);
        }

        //获取企业Id
        Map<String,Object> map=companyService.getCompanyId(tcpServiceRopo.getMachId());
        if(!(boolean)map.get("result")){
            resp.setCommandParam((String)map.get("code"));
            String rc=resp.getHexStr();
            return  HexUtil.decodeHex(rc);
        }
        Integer companyIdres=(Integer)map.get("companyId");

        RespMachMessage respMachMessage1=aiotClientService.changeBinDataState(companyIdres.longValue(),tcpServiceRopo.getMachId(),Integer.valueOf(recode));
        log.info("固件续传通知【{}】",respMachMessage1);
        if(!respMachMessage1.getCode().equals("0000")){
            resp.setCommandParam(respMachMessage1.getCode());
            String rc=resp.getHexStr();
            return  HexUtil.decodeHex(rc);
        }
        Map<String,Integer> map1=JSON.parseObject(JSON.toJSONString(respMachMessage1.getData()), Map.class);

        //响应结果  6个字节
        String param= "0000";
        StringBuilder stringBuilder=new StringBuilder(param);
        if(map1.get("flag")==0){
            stringBuilder.append("00");
        }else{
            stringBuilder.append("ff");
        }
        resp.setCommandParam(stringBuilder.toString());
        String rc=resp.getHexStr();
        return  HexUtil.decodeHex(rc);
    }
    //云卡通2.0黑/白名单全量/增量下传命令（0x0168/0x0170）
    @Override
    public byte[] whiteRecode(TcpServiceRopo tcpServiceRopo) throws Exception {
        //tcp参数
        //全量黑/白名单组号 4
        String code=tcpServiceRopo.getCommandParam().substring(0,8);

        //要返回的对象
        TcpServiceRopo resp=new TcpServiceRopo();

        //赋返回值  全是16进制字符串
        resp.setMachId(tcpServiceRopo.getMachId());
        resp.setEdition(tcpServiceRopo.getEdition());
        resp.setType(tcpServiceRopo.getType());
        resp.setPackageNum(tcpServiceRopo.getPackageNum());
        resp.setCommandType(tcpServiceRopo.getCommandType());

        //响应写死
        resp.setRespTip("02");
        //随机
        resp.setSessionId(tcpServiceRopo.getSessionId());

        //判断sessionId
        if(!checkSessionId(tcpServiceRopo)){
            resp.setCommandParam("0001");
            String rc=resp.getHexStr();
            return  HexUtil.decodeHex(rc);
        }


        //获取企业Id
        Map<String,Object> map=companyService.getCompanyId(tcpServiceRopo.getMachId());
        if(!(boolean)map.get("result")){
            resp.setCommandParam((String)map.get("code"));
            String rc=resp.getHexStr();
            return  HexUtil.decodeHex(rc);
        }
        Integer companyIdres=(Integer)map.get("companyId");

        String respMachMessageGson=accessDeviceClient.getWhiteList(Long.valueOf(String.valueOf(companyIdres)),tcpServiceRopo.getMachId(),2);//
        RespMachMessage respMachMessage1= JSON.parseObject(respMachMessageGson, RespMachMessage.class);
        if(!respMachMessage1.getCode().equals("0000")){
            resp.setCommandParam(respMachMessage1.getCode());
            String rc=resp.getHexStr();
            return  HexUtil.decodeHex(rc);
        }
        WhiteResp whiteResp= JSON.parseObject(JSON.toJSONString(respMachMessage1.getData()), WhiteResp.class);
        System.out.println(respMachMessage1);
        System.out.println(whiteResp);

        //增加/删除标志
        Integer flag=whiteResp.getFlag();
        flag=flag==1?2:1;
        //全量/增量标志
        Integer model=whiteResp.getModel();
        model++;
        //响应结果 10个字节 +黑/白名单卡号
        String param= "00000000000000000009";
        StringBuilder stringBuilder=new StringBuilder(param);
        stringBuilder.replace(5,6,flag.toString());
        stringBuilder.replace(7,8,model.toString());
//        stringBuilder.replace(5,6,"1");
//        stringBuilder.replace(7,8,"1");

        //全量黑名单标识为1时有效，不为1时填全0，跟请求的组号一样
        if(model==1){
            stringBuilder.replace(8,16,code);
        }else{
            stringBuilder.replace(8,16,"00000000");
        }
        String sizeHex="00";
        if(whiteResp.getList()!=null){
            sizeHex=NumConvertUtil.byteToHex(whiteResp.getList().size());
        }

        stringBuilder.replace(16,18,sizeHex);
        if(whiteResp.getList()!=null){
            //拼用户  卡号 4 人员编号 4 人员编号 1
            for (WhiteUser whiteUser:whiteResp.getList() ){
                //卡号
                if(whiteUser.getCard_No()==null || whiteUser.getCard_No().equals("")){
                    stringBuilder.append("ffffffff");
                }else{
                    stringBuilder.append(NumConvertUtil.reverseHex(NumConvertUtil.IntToHexStringNum(Integer.valueOf(whiteUser.getCard_No()),8)));
                }
                //pid  4个字节
                Integer pId=whiteUser.getP_ID();
                String pidStr=NumConvertUtil.reverseHex(NumConvertUtil.IntToHexStringNum(pId,8));
                stringBuilder.append(pidStr);
                //时区  1个字节
                stringBuilder.append(NumConvertUtil.IntToHexStringNum(whiteUser.getPergroupnum(),2));
            }
        }
        resp.setCommandParam(stringBuilder.toString());
        String rc=resp.getHexStr();
        System.out.println(rc);
        return  HexUtil.decodeHex(rc);
    }
    //云卡通2.0黑/白名单全量/增量下传结果通知（0x1168/0x1170）
    @Override
    public byte[] whiteRecodeResult(TcpServiceRopo tcpServiceRopo) throws Exception {
        //tcp参数
        //更新结果
        String result=tcpServiceRopo.getCommandParam();

        //要返回的对象
        TcpServiceRopo resp=new TcpServiceRopo();

        //赋返回值  全是16进制字符串
        resp.setMachId(tcpServiceRopo.getMachId());
        resp.setEdition(tcpServiceRopo.getEdition());
        resp.setType(tcpServiceRopo.getType());
        resp.setPackageNum(tcpServiceRopo.getPackageNum());
        resp.setCommandType(tcpServiceRopo.getCommandType());

        //响应写死
        resp.setRespTip("02");
        //随机
        resp.setSessionId(tcpServiceRopo.getSessionId());

        //判断sessionId
        if(!checkSessionId(tcpServiceRopo)){
            resp.setCommandParam("0001");
            String rc=resp.getHexStr();
            return  HexUtil.decodeHex(rc);
        }


        //成功
        if(result.equals("00")){
            //获取企业Id
            Map<String,Object> map=companyService.getCompanyId(tcpServiceRopo.getMachId());
            if(!(boolean)map.get("result")){
                resp.setCommandParam((String)map.get("code"));
                String rc=resp.getHexStr();
                return  HexUtil.decodeHex(rc);
            }
            Integer companyIdres=(Integer)map.get("companyId");

            RespMachMessage respMachMessage1=accessDeviceClient.changeWhiteListState(companyIdres.longValue(),tcpServiceRopo.getMachId());//
            if(!respMachMessage1.getCode().equals("0000")){
                resp.setCommandParam("0003");
                String rc=resp.getHexStr();
                return  HexUtil.decodeHex(rc);
            }
            System.out.println(respMachMessage1);
            //RespMachMessage{code='0000', msg='成功', data={flag=255}}
            Map<String,Integer> map2= JSON.parseObject(JSON.toJSONString(respMachMessage1.getData()), Map.class);
            if(map2.get("flag")==255){
                resp.setCommandParam("0000ff");
            }else{
                resp.setCommandParam("000000");
            }
            String rc=resp.getHexStr();
            System.out.println(rc);
            return  HexUtil.decodeHex(rc);
        }else{
            //设备无事件
            resp.setCommandParam("0501");
            String rc=resp.getHexStr();
            System.out.println(rc);
            return  HexUtil.decodeHex(rc);
        }
    }
    //上报设置二维码（0x8100）
    @Override
    public byte[] qrCode(TcpServiceRopo tcpServiceRopo) throws Exception {
        //TODO 直接写死的参数
        tcpServiceRopo.setCommandParam("0101ff01ff");
        //tcp参数
        //二维码类型
        String qrtType=tcpServiceRopo.getCommandParam().substring(0,2);
        //二维码长度
        String qrtLength=tcpServiceRopo.getCommandParam().substring(2,4);
        Integer len=NumConvertUtil.HexStringToInt(qrtLength);
        //二维码内容
        String qrtContent=tcpServiceRopo.getCommandParam().substring(4,len*2+4);
        //卡号长度
        String cardLength=tcpServiceRopo.getCommandParam().substring(len*2+4,len*2+6);
        //卡号
        String cardNo=tcpServiceRopo.getCommandParam().substring(len*2+6);


        //要返回的对象
        TcpServiceRopo resp=new TcpServiceRopo();

        //赋返回值  全是16进制字符串
        resp.setMachId(tcpServiceRopo.getMachId());
        resp.setEdition(tcpServiceRopo.getEdition());
        resp.setType(tcpServiceRopo.getType());
        resp.setPackageNum(tcpServiceRopo.getPackageNum());
        resp.setCommandType(tcpServiceRopo.getCommandType());

        //响应写死
        resp.setRespTip("02");
        //随机
        resp.setSessionId(tcpServiceRopo.getSessionId());

        //判断sessionId
        if(!checkSessionId(tcpServiceRopo)){
            resp.setCommandParam("0001");
            String rc=resp.getHexStr();
            return  HexUtil.decodeHex(rc);
        }

        //TODO 未实现
        if(qrtType.equals("02")){
            resp.setCommandParam("0003");
            String rc=resp.getHexStr();
            return  HexUtil.decodeHex(rc);
        }

        //获取企业Id
        Map<String,Object> map=companyService.getCompanyId(tcpServiceRopo.getMachId());
        if(!(boolean)map.get("result")){
            resp.setCommandParam((String)map.get("code"));
            String rc=resp.getHexStr();
            return  HexUtil.decodeHex(rc);
        }
        Integer companyIdres=(Integer)map.get("companyId");

        RespMachMessage respMachMessage1=accessDeviceClient.functionQr(companyIdres.longValue(),tcpServiceRopo.getMachId(),qrtContent);//
        System.out.println(respMachMessage1);
        if(!respMachMessage1.getCode().equals("0000")){
            resp.setCommandParam(respMachMessage1.getCode());
            String rc=resp.getHexStr();
            return  HexUtil.decodeHex(rc);
        }

        //响应结果  6个字节
        String param= "000000000000";

        StringBuilder stringBuilder=new StringBuilder(param);

        resp.setCommandParam(stringBuilder.toString());
        String rc=resp.getHexStr();
        return  HexUtil.decodeHex(rc);
    }
    //离线码秘钥更新(0x0105)
    @Override
    public byte[] updateKey(TcpServiceRopo tcpServiceRopo) throws Exception {
        //要返回的对象
        TcpServiceRopo resp=new TcpServiceRopo();

        //赋返回值  全是16进制字符串
        resp.setMachId(tcpServiceRopo.getMachId());
        resp.setEdition(tcpServiceRopo.getEdition());
        resp.setType(tcpServiceRopo.getType());
        resp.setPackageNum(tcpServiceRopo.getPackageNum());
        resp.setCommandType(tcpServiceRopo.getCommandType());

        //响应写死
        resp.setRespTip("02");
        //随机
        resp.setSessionId(tcpServiceRopo.getSessionId());

        //判断sessionId
        if(!checkSessionId(tcpServiceRopo)){
            resp.setCommandParam("0001");
            String rc=resp.getHexStr();
            return  HexUtil.decodeHex(rc);
        }

        //获取企业Id
        Map<String,Object> map=companyService.getCompanyId(tcpServiceRopo.getMachId());
        if(!(boolean)map.get("result")){
            resp.setCommandParam((String)map.get("code"));
            String rc=resp.getHexStr();
            return  HexUtil.decodeHex(rc);
        }
        Integer companyIdres=(Integer)map.get("companyId");

        RespMachMessage respMachMessage1=accessDeviceClient.getDecodeKey(companyIdres.longValue(),tcpServiceRopo.getMachId(),1);
        System.out.println(respMachMessage1);
        if(!respMachMessage1.getCode().equals("0000")){
            resp.setCommandParam(respMachMessage1.getCode());
            String rc=resp.getHexStr();
            return  HexUtil.decodeHex(rc);
        }

        Secret secret=JSON.parseObject(JSON.toJSONString(respMachMessage1.getData()), Secret.class);
        System.out.println(secret);

//        响应结果	2
//        JobID	6
        String param= "0000";
        StringBuilder stringBuilder=new StringBuilder(param);
        stringBuilder.append(NumConvertUtil.IntToHexStringNum(secret.getJobId(),12));

        //Secret(jobId=1, code_mode=0, secret={public_key=f63a57298ee48fe8, next_public=f63a57298ee48fe8, prev_public=f63a57298ee48fe8})

        byte[] publicKey=NumConvertUtil.hexStringToByte(secret.getSecret().get("public_key"));
        byte[] nextPublicKey=NumConvertUtil.hexStringToByte(secret.getSecret().get("next_public"));
        byte[] prevPublicKey=NumConvertUtil.hexStringToByte(secret.getSecret().get("prev_public"));

        stringBuilder.append(NumConvertUtil.IntToHexStringNum(publicKey.length,2));
        stringBuilder.append(secret.getSecret().get("public_key"));
        stringBuilder.append(NumConvertUtil.IntToHexStringNum(prevPublicKey.length,2));
        stringBuilder.append(secret.getSecret().get("prev_public"));
        stringBuilder.append(NumConvertUtil.IntToHexStringNum(nextPublicKey.length,2));
        stringBuilder.append(secret.getSecret().get("next_public"));

        resp.setCommandParam(stringBuilder.toString());
        String rc=resp.getHexStr();
        System.out.println(rc);
        return  HexUtil.decodeHex(rc);
    }
    //离线码秘钥更新通知(0x1105)
    @Override
    public byte[] updateKeyResult(TcpServiceRopo tcpServiceRopo) throws Exception {
        //tcp参数
        //记录号 6
        System.out.println(tcpServiceRopo);
        String JobID=tcpServiceRopo.getCommandParam().substring(0,12);
        //改整形
        JobID=NumConvertUtil.HexStringToInt(JobID).toString();
        //更新结果 1
        String result=tcpServiceRopo.getCommandParam().substring(12,14);

        //要返回的对象
        TcpServiceRopo resp=new TcpServiceRopo();

        //赋返回值  全是16进制字符串
        resp.setMachId(tcpServiceRopo.getMachId());
        resp.setEdition(tcpServiceRopo.getEdition());
        resp.setType(tcpServiceRopo.getType());
        resp.setPackageNum(tcpServiceRopo.getPackageNum());
        resp.setCommandType(tcpServiceRopo.getCommandType());

        //响应写死
        resp.setRespTip("02");
        //随机
        resp.setSessionId(tcpServiceRopo.getSessionId());


        //判断sessionId
        if(!checkSessionId(tcpServiceRopo)){
            resp.setCommandParam("0001");
            String rc=resp.getHexStr();
            return  HexUtil.decodeHex(rc);
        }

        if(!result.equals("00")){
            resp.setCommandParam("000300");
            String rc=resp.getHexStr();
            return  HexUtil.decodeHex(rc);
        }

        //获取企业Id
        Map<String,Object> map=companyService.getCompanyId(tcpServiceRopo.getMachId());
        if(!(boolean)map.get("result")){
            resp.setCommandParam((String)map.get("code"));
            String rc=resp.getHexStr();
            return  HexUtil.decodeHex(rc);
        }
        Integer companyIdres=(Integer)map.get("companyId");

        RespMachMessage respMachMessage1=accessDeviceClient.changeKeyState(companyIdres.longValue(),tcpServiceRopo.getMachId(),JobID,1);//
        System.out.println(respMachMessage1);
        if(!respMachMessage1.getCode().equals("0000")){
            resp.setCommandParam(respMachMessage1.getCode());
            String rc=resp.getHexStr();
            return  HexUtil.decodeHex(rc);
        }

        Map<String,Integer> map1=JSON.parseObject(JSON.toJSONString(respMachMessage1.getData()), Map.class);

        //响应结果  6个字节
        String param= "0000";
        StringBuilder stringBuilder=new StringBuilder(param);
        if(map1.get("updataFlag")==0){
            stringBuilder.append("00");
        }else{
            stringBuilder.append("ff");
        }

        resp.setCommandParam(param);
        String rc=resp.getHexStr();
        System.out.println(rc);
        return  HexUtil.decodeHex(rc);
    }

    /**
     * 验证sessionIs
     * @param tcpServiceRopo
     * @return
     */
    public  boolean checkSessionId(TcpServiceRopo tcpServiceRopo){
        String session=(String) redisUtil.hmGet("tcpMach:"+tcpServiceRopo.getMachId(),"session");
        if(!tcpServiceRopo.getSessionId().equals(session)){
            return false;
        }else{
            return true;
        }
    }




}
